<template>
  <div class="menu-wrap">
    <a-menu
      mode="inline"
      theme="dark"
      :openKeys="openKeys"
      :defaultSelectedKeys="defaultSelectedKeys"
      @openChange="onOpenChange"
      :inlineCollapsed="collapsed"
    >
      <template v-for="item in routerMap">
        <a-sub-menu :key="item.path">
          <span slot="title">
            <a-icon :type="item.icon || 'tags'"/>
            <span>{{item.title}}</span>
          </span>
          <a-menu-item
            v-for="childrenItem in item.children"
            :key="childrenItem.path"
            v-show="checkIsHide(childrenItem)"
            @click="toPage(childrenItem.path)"
          >{{childrenItem.meta.title}}</a-menu-item>
        </a-sub-menu>
        <!-- <a-menu-item v-else :key="item.path" @click="toPage(item.path)">
          <a-icon :type="item.meta.icon || 'tags'"/>
          <span>{{item.meta.title}}</span>
        </a-menu-item>-->
      </template>
    </a-menu>
  </div>
</template>

<script>
import routerMap from '../router/menu'
const getKeyArr = routerMap.map(item => item.path)
export default {
  data() {
    return {
      routerMap,
      collapsed: false,
      rootSubmenuKeys: getKeyArr,
      openKeys: [], // 一级路由
      defaultSelectedKeys: null // 默认二级路由
    }
  },
  created() {
    const path = this.$route.path
    const rootMenu = path.split('/')[2]
    const childMenu = path.split('/')[3]
    this.openKeys.push(rootMenu)
    this.defaultSelectedKeys = [`${rootMenu}/${childMenu}`]
  },
  methods: {
    checkIsHide(item) {
      if (item.meta && item.meta.isHidden && item.meta.isHidden === 'hide') {
        return false
      } else {
        return true
      }
    },
    toggleCollapsed() {
      this.collapsed = !this.collapsed
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(
        key => this.openKeys.indexOf(key) === -1
      )
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    },
    toPage(path) {
      this.$router.push(`/menu/${path}`)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
